<template>
    <div>
        <div id="searchIndex" @click="setupWatcher(1)"
            style="width: 0;height: 0;opacity: 0;position: fixed;overflow: hidden;"></div>
        <div>
            <!-- <a-spin :spinning="loading" size="large" class="loading-spinner" /> -->
        </div>
        <div class="Ivstandard show-pc">
            <div>
                <div class="title">

                </div>
                <div class="title2">
                    <div class="title_lift">{{ labelName }}</div>
                    <div class="title_right">
                        <div>排序：</div>
                        <div class="simple-tabs">
                            <div v-for="(tab, index) in prevent" :key="index"
                                :class="{ 'active': activeIndex === index }" @click="selectIndex(tab)">
                                {{ tab.name }}
                            </div>
                        </div>
                    </div>
                </div>

                <div class="WaterfallFlow">
                    <div class="LeftNavigation"> </div>

                    <div class="LeftNavigation2">
                        <!-- 全部选项 -->
                        <div class="Left_title" @click="handleAll(allList)"
                            :class="{ 'selected': activeTab === 'all' }">
                            <div class="text">全部</div>
                        </div>


                        <!-- 可滚动的内容区域 -->
                        <div class="scrollable-content" style="height: 70%;">

                            <div v-for="(item, index) in tabsprevent" :key="index">
                                <div class="Select" :class="{ 'selected': activeTab === item.columnId }"
                                    @click="selectItem(item)">
                                    <div class="Select_text">{{ item.columnName }}</div>
                                    <div v-if="item.children !== null">
                                        <DownOutlined :style="{
                                            transform: `${(item.children && activeItemId === item.columnId) ? 'rotate(-180deg)' : 'rotate(0deg)'}`,
                                            transition: 'all .3s'
                                        }" />
                                    </div>
                                </div>

                                <!-- 子菜单 -->
                                <div v-if="item.children && activeItemId === item.columnId" class="children-list">
                                    <div v-for="son in item.children" :key="son.columnId" class="childrenItem"
                                        :class="{ 'selected': activeTab === son.columnId }" @click="selectItem(son)">
                                        {{ son.columnName }}
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

                    <div class="WaterfallFlow_item" ref="waterfallContainer">
                        <Waterfall :col="3" :data-source="list" :show-icon="true" :dataStatus="dataStatus"
                            :loading="loading" ref="WaterfallRef" @openEdit="openEdit" @loadData="loadData">
                            <template #default="{ item }" v-if="showData">
                                <Card :item="item" />
                            </template>
                        </Waterfall>


                        <!-- <div class="back-to-top" :class="{ show: showBackToTop }" @click="scrollToTop">
                            <ArrowUpOutlined />
                        </div> -->
                    </div>
                </div>
            </div>
        </div>

        <div class="show-wap">
            <div>
                <div class="title-wap">
                    <div>
                        <!-- 类别下拉菜单 -->
                        <a-dropdown v-model:visible="tabsVisible" :trigger="['click']" placement="bottomRight"
                            overlayClassName="custom-dropdown-all">
                            <a class="ant-dropdown-link">
                                {{ allDisplayText }}
                                <DownOutlined :class="['arrow-icon-all', { 'arrow-up-all': tabsVisible }]" />
                            </a>
                            <template #overlay>
                                <a-menu>
                                    <a-menu-item
                                        :class="['custom-menu-item', { 'selected-menu-item': selectedAllItem === -1 }]"
                                        @click="handleAllMenuClick(allList)">
                                        <span class="menu-item-text" style="color: var(--color-text-6);">全部</span>
                                    </a-menu-item>

                                    <a-menu-item v-for="(item, index) in tabsprevent" :key="index"
                                        :class="['custom-menu-item', { 'selected-menu-item': selectedAllItem === index }]"
                                        @click="handleAllMenuClick(item)">
                                        <span class="menu-item-text" style="color: var(--color-text-6);">{{
                                            item.columnName
                                        }}</span>
                                    </a-menu-item>
                                </a-menu>
                            </template>
                        </a-dropdown>
                    </div>
                    <div>
                        <!-- 排序下拉菜单 -->
                        <a-dropdown v-model:visible="dropdownVisible" :trigger="['click']" placement="bottomRight"
                            overlayClassName="custom-dropdown-sort">
                            <a class="ant-dropdown-link">
                                {{ sortDisplayText }}
                                <DownOutlined :class="['arrow-icon', { 'arrow-up': dropdownVisible }]" />
                            </a>
                            <template #overlay>
                                <a-menu>
                                    <a-menu-item v-for="(item, index) in prevent" :key="index"
                                        :class="['custom-menu-item', { 'selected-menu-item': selectedSortItem === index }]"
                                        @click="handleSortMenuClick(item)">
                                        <span class="menu-item-text" style="color: var(--color-text-6);">{{ item.name
                                            }}</span>
                                    </a-menu-item>
                                </a-menu>
                            </template>
                        </a-dropdown>
                    </div>
                </div>
                <div class="sub-frame">
                    <div class="sub-item" v-for="(item, index) in childrenWap"
                        :class="{ 'sub-item-active': queryParams.columnId == item.columnId }"
                        @click="handleAllMenuClick(item)">
                        {{ item.columnName }}
                    </div>
                </div>
                <div class="WaterfallFlow_item-wap">
                    <Waterfall :key="componentKey" :col="3" :data-source="list" :show-icon="true"
                        :dataStatus="dataStatus" :loading="loading" ref="WaterfallRef2" @openEdit="openEdit"
                        @loadData="loadData">
                        <template #default="{ item }">
                            <Card :item />
                        </template>
                    </Waterfall>
                </div>
            </div>
        </div>

    </div>
</template>

<script setup>
import Waterfall from '@/components/Waterfall/index.vue'
import { useStore } from '@/store'
import { useHttp } from '@/api/http'
import { ref, onMounted, watch, getCurrentInstance } from 'vue'
import { useRoute } from 'vue-router';
import qs from 'qs'


const { proxy } = getCurrentInstance()
const forceUpdate = () => { proxy.$forceUpdate() }
const { themeStore } = useStore()
const router = useRouter();
const route = useRoute();
const labelName = ref('');
const tabsVisible = ref(false);
const dropdownVisible = ref(false);
const selectedAllItem = ref(null);
const selectedSortItem = ref(null);
const waterfallContainer = ref(null); // 获取瀑布流滚动容器
const showBackToTop = ref(false);     // 瀑布流控制按钮显示

// 当前要显示子项的栏目 ID
const activeItemId = ref(null)

// 使用单一状态变量，初始值为'all'表示默认选中全部
const activeTab = ref('all')
const tabsprevent = ref([]);
const allList = ref({
    children: null,
    columnIcon: "",
    columnIconSelected: "",
    columnId: "",
    columnName: "全部",
    orderNum: "",
    parentId: "",
})
const LargeColumn = ref([])
const showData = ref(false)

const activeIndex = ref(0);
const prevent = ref([
    // { name: '全部', id: '', index: 0 },
    { name: '热门下载', id: 2, index: 0 },
    { name: '最新上传', id: '', index: 1 }
]);



// 瀑布流处理滚动事件
const handleScroll = () => {
    showBackToTop.value = waterfallContainer.value.scrollTop > 300;
};

// 瀑布流平滑滚动到顶部
const scrollToTop = () => {
    waterfallContainer.value.scrollTo({
        top: 0,
        behavior: 'smooth'
    });
};





const queryParams = ref({
    columnId: labelName.value,
    pageSize: 15,
    pageNo: 1,
    sortType: '',
})
const list = ref([])

// 加载状态控制
const loading = ref(false)
const dataStatus = ref(true)


// 栏目下的子级
const columnIdList = ref({
    columnId: '',
})



const allDisplayText = computed(() => {
    return selectedAllItem.value !== null
        ? selectedAllItem.value
        : '类别';
});

const sortDisplayText = computed(() => {
    return selectedSortItem.value !== null
        ? selectedSortItem.value
        : '排序';
});
const childrenWap = ref([])
// 手机类别下拉
const handleAllMenuClick = (item) => {
    if (item.children) {
        childrenWap.value = item.children
    }
    selectedAllItem.value = item.columnName;
    tabsVisible.value = false;
    queryParams.value.columnId = item.columnId

    list.value = []
    queryParams.value.pageNo = 1
    dataStatus.value = true
    getpicColumnList()
};
// 手机端下啦排序
const handleSortMenuClick = (item) => {
    selectedSortItem.value = item.name;
    dropdownVisible.value = false;
    queryParams.value.sortType = item.id
    activeIndex.value = item.index
    list.value = []
    queryParams.value.pageNo = 1
    dataStatus.value = true
    setupWatcher();
};


// 全部选项点击处理
const handleAll = (item) => {
    activeTab.value = 'all' // 设置激活状态为全部
    queryParams.value.columnId = item.columnId
    queryParams.value.pageNo = 1
    list.value = []
    dataStatus.value = true
    window.scrollTo(0, 0);
    getpicColumnList()
}

// 子栏目点击处理
const selectItem = (item) => {
    activeTab.value = item.columnId // 设置激活状态为当前子栏目
    queryParams.value.columnId = item.columnId
    queryParams.value.pageNo = 1
    list.value = []
    dataStatus.value = true
    window.scrollTo(0, 0);

    if (item.children !== null) {
        if (activeItemId.value === item.columnId) {

            activeItemId.value = null
        } else {

            activeItemId.value = item.columnId
        }
    }


    getpicColumnList()
}
// 卸载前移除事件监听器
onBeforeUnmount(() => {
    document.removeEventListener('visibilitychange', handleVisibilityChange)
    window.removeEventListener('beforeunload', handleBeforeUnload)
    waterfallContainer.value?.removeEventListener('scroll', handleScroll); //瀑布流滚动
});
const newVal = ref({})
// onMounted(() => {
//     document.addEventListener('visibilitychange', handleVisibilityChange)
//     window.addEventListener('beforeunload', handleBeforeUnload)

//     for (let i in route.query) {
//         queryParams.value[i] = route.query[i]
//     }
//     waterfallContainer.value.addEventListener('scroll', handleScroll);//瀑布流滚动







// })

onMounted(() => {
    // 注册事件监听
    document.addEventListener('visibilitychange', handleVisibilityChange)
    window.addEventListener('beforeunload', handleBeforeUnload)

    // 初始化查询参数
    for (let i in route.query) {
        queryParams.value[i] = route.query[i]
    }

    // 绑定瀑布流滚动事件
    if (waterfallContainer.value) {
        waterfallContainer.value.addEventListener('scroll', handleScroll)
    }

    // 参数判断逻辑
    const currentQuery = route.query
    const allParamsEmpty = Object.values(currentQuery).every(
        value => value === '' || value === undefined || value === null
    )

    // 判断 columnId 是否为空（包括不存在的情况）
    const isColumnIdEmpty =
        currentQuery.columnId === '' ||
        currentQuery.columnId === undefined ||
        currentQuery.columnId === null

    // 跳转条件
    if (
        (Object.keys(currentQuery).length > 0 && allParamsEmpty) ||
        isColumnIdEmpty
    ) {
        // 刷新式跳转到首页（会重新加载页面）
        window.location.href = '/'  // 关键修改：使用location.href实现刷新跳转
    }
})


//定义处理焦点变化的方法
const handleVisibilityChange = () => {

    if (document.visibilityState === 'visible') {
        if (location.href.includes('standardPath?')) {
            newVal.value = qs.parse(location.href.split('standardPath?')[1])
            themeStore.activeKey = Number(newVal.value.activeKey);
        }

    } else {
        // console.log('用户离开了当前页面')
    }

};
// 页面即将关闭或刷新（如点击链接、刷新、关闭窗口）
const handleBeforeUnload = (e) => {
    //   pageState.value = 'leaving'

    //   const confirmationMessage = '你确定要离开吗？数据可能未保存！'
    //   e.returnValue = confirmationMessage // Gecko + Webkit
    //   return confirmationMessage // IE
}


// 首页点击跳转后
const setupWatcher = (type = 1) => {

    if (type === 1) {
        newVal.value = themeStore.searcShow
        activeTab.value = "all"
    } else {
        newVal.value = { ...route.query }
        themeStore.activeKey = Number(newVal.value.activeKey);
    }
    // let newVal = themeStore.searcShow
    LargeColumn.value = newVal.value.columnId
    queryParams.value.columnId = newVal.value.columnId
    labelName.value = newVal.value.title;
    columnIdList.value.columnId = newVal.value.columnId;
    queryParams.value.keyWord = newVal.value.keyWord || ''
    allList.value.columnId = newVal.value.columnId

    list.value = []
    queryParams.value.pageNo = 1
    dataStatus.value = true
    loading.value = false
    selectedAllItem.value = null
    window.scrollTo(0, 0);
    getData();
    getpicColumnList()

};





const getData = () => {
    // 查询栏目下的子级栏目
    useHttp.get('/web/index/getByColumnIdList', columnIdList.value).then((res) => {
        tabsprevent.value = res.result;

        forceUpdate()
    })
}
// 查询瀑布流
const getpicColumnList = () => {
    if (!dataStatus.value || loading.value) return
    loading.value = true
    useHttp.get('/web/index/picColumnList', queryParams.value).then((res) => {

        loading.value = false
        list.value.push(...res.result.records)
        if (res.result.records.length < queryParams.value.pageSize) {
            dataStatus.value = false
        }
    })
}






// 素材
const openEdit = (item, index) => {
    UploadWorksRef.value.edit(item, index)
}

// 分页加载
const loadData = () => {
    if (list.value.length === 0) return
    queryParams.value.pageNo += 1
    getpicColumnList()
}



// 排序点击事件
const selectIndex = (item) => {
    dataStatus.value = true
    queryParams.value.pageNo = 1
    queryParams.value.sortType = item.id
    activeIndex.value = item.index
    window.scrollTo(0, 0);
    setupWatcher();
}


setupWatcher(2);
</script>

<style lang="less" scoped>
.Ivstandard {
    width: 95.83333333333334vw;
    margin: 0 auto;
    margin-top: 40px;


    .title {
        width: 100%;
        height: 50px;
        display: flex;
        justify-content: space-between;
        line-height: 50px;

    }

    .title2 {
        width: 95.83333333vw;
        height: calc(50px + 1.7vw);
        display: flex;
        justify-content: space-between;
        position: fixed;
        top: 4.3vw;
        background-color: var(--color-bg-F6);
        z-index: 100;
        align-items: center;



        .title_lift {

            height: 1.14vw;
            font-family: MicrosoftYaHei-Bold;
            font-size: 1.14vw;
            color: var(--color-text-3);
        }



        .title_right {

            display: flex;
            justify-content: space-around;
            gap: 20px;
            font-size: 0.83vw;
            color: var(--color-text);


            .simple-tabs {
                display: flex;
                gap: 20px;
            }

            .simple-tabs div {
                cursor: pointer;
            }

            .simple-tabs div.active {
                color: var(--color-Sel);
            }
        }
    }



    .WaterfallFlow {
        display: flex;
        justify-content: space-around;

        .LeftNavigation {
            width: 13vw;
            height: 100vh;
            margin-top: 0.88vw;
            // box-shadow: 15px 0 20px -15px rgba(120, 120, 120, 0.1),
            //     -15px 0 20px -15px rgba(120, 120, 120, 0.1);
            border-radius: 0.20vw;
            // background-color: var(--color-bg-20);
            // border: 1px solid red;
        }

        /* 滚动容器样式 */
        .scrollable-content {
            overflow-y: auto;
            -webkit-overflow-scrolling: touch;
            /* 移动端流畅滚动 */
            height: 70%;
            /* 确保设置了固定高度 */

        }

        /* WebKit 浏览器（Chrome / Edge / Safari） */
        .scrollable-content::-webkit-scrollbar {
            width: 6px;
            /* 滚动条宽度 */
        }

        /* 设置滚动条轨道透明 */
        .scrollable-content::-webkit-scrollbar-track {
            background: transparent;
            /* 轨道背景透明 */
            border-radius: 3px;
        }

        /* 滚动条滑块 */
        .scrollable-content::-webkit-scrollbar-thumb {
            background: #ccc;
            /* 滑块颜色 */
            border-radius: 3px;
        }

        .scrollable-content::-webkit-scrollbar-thumb:hover {
            background: #aaa;
            /* 鼠标悬停时滑块颜色变深 */
        }

        /* Firefox 滚动条样式 */
        .scrollable-content {
            scrollbar-width: thin;
            /* 或者 'auto'/'none' */
            scrollbar-color: #ccc transparent;
            /* 第一个值是滑块颜色，第二个值是轨道颜色（透明） */
        }

        .LeftNavigation2 {
            width: 13vw;
            height: 100vh;
            margin-top: 0.88vw;
            box-shadow: 15px 0 20px -15px rgba(120, 120, 120, 0.1), -15px 0 20px -15px rgba(120, 120, 120, 0.1);
            border-radius: 0.20vw;
            background-color: var(--color-bg-20);
            position: fixed;
            left: 2.083333335vw;
            overflow-y: auto;

            .Left_title {
                width: 100%;
                height: 1.97vw;
                display: flex;
                justify-content: space-between;
                font-size: var(--text-16);
                color: var(--color-text);
                // color: var(--text-color);
                // background-color: var(--ba-sel);
                line-height: 1.97vw;
                border-radius: 2px;


                .text {
                    width: 20%;
                    text-align: center;
                    font-size: 0.83vw;
                    margin-left: 0.52vw;
                    cursor: pointer;
                }

                .jiantou {
                    width: 20%;
                    text-align: center;
                    margin-right: 0.52vw;

                    >img {
                        width: 1vw;
                        height: 0.53vw;
                    }
                }
            }

            .Select {
                width: 100%;
                height: 1.97vw;
                display: flex;

                align-items: center;
                padding-left: 0.72vw;
                font-size: var(--text-16);
                color: var(--color-text);


                .Select_png {
                    width: auto;

                    >img {

                        width: 0.9vw;
                        height: 0.8vw;
                    }
                }

                .Select_text {
                    width: auto;
                    margin-left: 0.4vw;

                    cursor: pointer;
                    padding-right: 0.3vw;
                }



            }

            .childrenItem {
                width: 100%;
                height: 1.97vw;
                display: flex;

                align-items: center;
                padding-left: 1.7vw;
                font-size: var(--text-16);
                color: var(--color-text);
                cursor: pointer;

            }

        }

        .WaterfallFlow_item {
            flex: 1;
            margin-left: 1.04vw;
            margin-top: 0.88vw;
            height: 100vh;
            position: relative;


        }
    }

}

.selected {
    background-color: var(--ba-sel);

}

.selected .Select_text {
    color: var(--ba-sel-t);
}

.selected {
    background-color: var(--ba-sel);
    /* 使用相同的选中背景色 */
}

.selected .text {
    color: var(--ba-sel-t);

}




// 手机样式
.show-wap {
    width: 95%;
    margin: 0 auto;

    .title-wap {
        width: 100%;
        height: 50px;
        display: flex;
        align-items: center;
        gap: 18px;

        .ant-dropdown-link {
            font-size: 16px;
            color: var(--color-text-3);
            display: flex;
            align-items: center;
        }

        // 箭头样式
        .arrow-icon,
        .arrow-icon-all {
            transition: transform 0.3s ease;
            margin-left: 8px;
            color: var(--color-text-3);

            &.arrow-up,
            &.arrow-up-all {
                transform: rotate(180deg);
            }
        }

        // 菜单项样式
        :deep(.custom-menu-item) {

            padding: 5px 12px !important;

            .menu-item-text {
                display: inline-block;
                border: 1px solid red;
            }




        }

        .ant-dropdown-menu-title-content {
            color: red !important;
        }

        :deep(.ant-menu-item-selected) {
            background-color: transparent !important;
        }
    }



    /* 选中状态样式 */
    .Select-wap.selected-wap .Select_text-wap {
        color: var(--color-Sel);
    }

    .Select-wap.selected-wap::after {
        content: "";
        position: absolute;
        bottom: 0;
        left: 50%;
        transform: translateX(-50%);
        width: 100%;
        height: 2px;
        background-color: var(--color-Sel);
    }


    .WaterfallFlow_item-wap {
        flex: 1;
        // margin-left: 20px;
        // margin-top: 17px;
        padding-bottom: 80px;



    }
}

.sub-frame {
    padding-bottom: 10px;
    display: flex;
    align-items: center;
    flex-wrap: wrap;

    .sub-item {
        height: 28px;
        padding: 0 10px;
        border: 1px solid #ddd;
        border-radius: 4px;
        margin-right: 10px;
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 13px;
        color: var(--color-text-6);
    }

    .sub-item-active {
        background-color: var(--ba-sel);
    }
}
</style>